//
//  HMComposeToolBar.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/4.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

enum HMComposeToolBarButtonType:Int {
    //图片
    case picture = 0
    //@
    case mention = 1
    //#
    case trend = 2
    //表情
    case emoticon = 3
    //加号
    case add = 4
}

class HMComposeToolBar: UIStackView {

    //回调的闭包
    var callBack:((HMComposeToolBarButtonType)->())?
    //记录表情按钮
    var emoticonButton:UIButton?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        backgroundColor = UIColor.red
        //水平布局
        axis = .horizontal
        //子控件填充方式
        distribution = .fillEqually
        addChildButton(imageName: "compose_toolbar_picture",type: .picture)
        addChildButton(imageName: "compose_mentionbutton_background",type: .mention)
        addChildButton(imageName: "compose_trendbutton_background",type: .trend)
        emoticonButton = addChildButton(imageName: "compose_emoticonbutton_background",type: .emoticon)
        addChildButton(imageName: "compose_add_background",type: .add)
    }

    //
    
    //添加子控件的方法
    @discardableResult //不关心返回结果
    private func addChildButton(imageName:String,type:HMComposeToolBarButtonType) -> UIButton {
        let button = UIButton()
        //枚举值设置为tag
        button.tag = type.rawValue
        button.addTarget(self, action: #selector(buttonClick(btn:)), for: .touchUpInside)
        button.setImage(UIImage(named:"\(imageName)"), for: .normal)
        button.setImage(UIImage(named:"\(imageName)_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named:"compose_toolbar_background"), for: .normal)
        //去掉点击效果
        button.adjustsImageWhenHighlighted = false
        //添加子控件
        addArrangedSubview(button)
        return button
    }
    
    //子控件的点击事件
    @objc private func buttonClick(btn:UIButton) {
        //根据枚举的原始值创建枚举
        let type = HMComposeToolBarButtonType(rawValue:btn.tag)!
        
        callBack?(type)
        
    }
    
    //根据表情键盘的类型显示对应的icon
    func showIcon(isEmoticon:Bool) {
        //如果是表情键盘显示系统的icon
        if isEmoticon {
            emoticonButton?.setImage(UIImage(named:"compose_keyboardbutton_background"), for: .normal)
            emoticonButton?.setImage(UIImage(named:"compose_keyboardbutton_background_highlighted"), for: .highlighted)
        }else{
            //如果是系统键盘显示表情键盘的icon
            emoticonButton?.setImage(UIImage(named:"compose_emoticonbutton_background"), for: .normal)
            emoticonButton?.setImage(UIImage(named:"compose_emoticonbutton_background_highlighted"), for: .highlighted)
        }
        
        
    }
}
